import { Emitter } from '@/enum/emitter'
import mitt from 'mitt'
import { setBaseUrl } from '@/service/request'
import { useRoute } from 'vue-router'
import { ref, onUnmounted, onMounted } from 'vue'

const emitter = mitt()

export const useEmitter = () => {
  const _on = (key: keyof typeof Emitter, cb: () => void) => emitter.on(key, cb)
  const _emit = (key: keyof typeof Emitter) => emitter.emit(key)
  const _off = (key: keyof typeof Emitter, cb: () => void) => emitter.off(key, cb)

  return {
    on: _on,
    emit: _emit,
    off: _off
  }
}

export const useScheduler = (callback: () => void, delay: number) => {
  const timer = ref<any>()

  function start () {
    timer.value = setInterval(callback, delay)
  }

  function stop () {
    clearInterval(timer.value)
  }

  onUnmounted(() => {
    stop()
  })

  return {
    start,
    stop
  }
}

export const useSchedulerOnce = (callback: () => void, delay: number) => {
  const timeId = ref()
  timeId.value = setTimeout(() => {
    callback()
    clearTimeout(timeId.value)
  }, delay)

  onUnmounted(() => {
    clearTimeout(timeId.value)
  })
}

export const usePort = (title: string) => {
  console.log('process.env:', process.env)

  if (process.env.NODE_ENV === 'development') {
    setBaseUrl('/api')
  } else {
    setBaseUrl('http://39.96.117.178:3037')
  }
}

/**
 * `useDeviceResolution` 函数是一个 TypeScript 函数，允许您跟踪设备的屏幕宽度和高度，并在屏幕大小调整时执行回调函数。
 * @param {Function} cb - 参数“cb”是一个回调函数，每当设备分辨率发生变化时就会调用该函数。
 * @returns 函数“useDeviceResolution”返回一个具有两个属性的对象：“screenWidth”和“screenHeight”。
 */
export const useDeviceResolution = (cb: Function) => {
  const screenWidth = ref(window.innerWidth)
  const screenHeight = ref(window.innerHeight)

  const handleResize = () => {
    screenWidth.value = window.innerWidth
    screenHeight.value = window.innerHeight
    cb()
  }

  onMounted(() => {
    window.addEventListener('resize', handleResize)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
  })

  return {
    screenWidth,
    screenHeight
  }
}

/**
 *  @description 获取当前模块信息
 *  @example
 *  const module = useModule()
 *  console.log(module.name)
 *  console.log(module.path)
 */
export const useModule = () => {
  const route = useRoute()
  return {
    name: route.matched[0].name,
    path: route.matched[0].path
  }
}
